package com.yulang.security.core.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.yulang.security.core.config.ImageCodeConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
@RequestMapping
public class CustomLoginController {

    public final static String SESSION_KEY_IMAGE_CODE = "session_key_image_code";

    @Autowired
    private ImageCodeConfig imageCodeConfig;

    @RequestMapping("/code/image")
    public void imageCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        DefaultKaptcha defaultKaptcha = imageCodeConfig.getDefaultKaptcha();
        String kaptchaText = defaultKaptcha.createText();
        request.getSession().setAttribute(SESSION_KEY_IMAGE_CODE,kaptchaText);
        BufferedImage image = defaultKaptcha.createImage(kaptchaText);
        ServletOutputStream stream = response.getOutputStream();
        ImageIO.write(image,"jpg",stream);
    }

}
